package cfig.toolset

import se.vidstige.jadb.JadbDevice

@ExperimentalStdlibApi
class BootCtl() {
    private lateinit var dut: JadbDevice
    var halInfo: String = ""
    var currentSlot: Int = -1
    var slotNum: Int = -1
    var slots: MutableList<SlotInfo> = mutableListOf()

    @ExperimentalStdlibApi
    constructor(inDut: JadbDevice) : this() {
        dut = inDut
        halInfo = dut.executeShell("bootctl hal-info").readBytes().decodeToString().trim()
        currentSlot = dut.executeShell("bootctl get-current-slot").readBytes().decodeToString().trim().toInt()
        slotNum = dut.executeShell("bootctl get-number-slots").readBytes().decodeToString().trim().toInt()
        for (i in 0 until slotNum) {
            slots.add(SlotInfo(slot = i,
                    suffix = getSlotSuffix(i),
                    bBootable = getSlotBootable(i),
                    bMarkedSuccess = getSlotMarkedSuccess(i)))
        }
    }

    data class SlotInfo(
            var slot: Int = 0,
            var suffix: String = "",
            var bBootable: Boolean = false,
            var bMarkedSuccess: Boolean = false
    )

    fun getSlotSuffix(slot: Int): String {
        return dut.executeShell("bootctl get-suffix $slot").readBytes().decodeToString().trim()
    }

    fun getSlotBootable(slot: Int): Boolean {
        return AdbTool().shellCheckCall(dut, "bootctl is-slot-bootable $slot")
    }

    fun getSlotMarkedSuccess(slot: Int): Boolean {
        return AdbTool().shellCheckCall(dut, "bootctl is-slot-marked-successful $slot")
    }

    fun setUnBootable(slot: Int) {
        assert(AdbTool().shellCheckCall(dut, "bootctl set-slot-as-unbootable $slot"))
    }

    fun markSuccess(slot: Int) {
        assert(AdbTool().shellCheckCall(dut, "bootctl mark-boot-successful $slot"))
    }

    fun setActiveSlot(slot: Int) {
        assert(AdbTool().shellCheckCall(dut, "bootctl set-active-boot-slot $slot"))
    }

    override fun toString(): String {
        return "BootCtl(dut=${dut.serial}, halInfo='$halInfo', currentSlot=$currentSlot, slotNum=$slotNum, slots=$slots)"
    }
}
